import { login, logout, getInfo } from '@/api/login'
import {
  getToken,
  setToken,
  removeToken,
  getUserId,
  setUserId,
  removeUserId,
  setUserName,
  getUserName,
  removeUserName,
  getUserAvatar,
  setUserAvatar,
  removeUserAvatar,
} from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import Aes from '@/utils/aes'


const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    id: '',
    name: getUserName(),
    avatar: getUserAvatar(),
    roles: [],
    permissions: [],
    userId: getUserId(),
  }),
  actions: {
    // 登录
    login(userInfo) {
      const username = userInfo.username.trim()
      const password = Aes.encrypt(userInfo.password)
      return new Promise((resolve, reject) => {
        login(username, password).then((res) => {
            let data = res.data
            setUserName(data.user.loginName)
            setUserAvatar(data.user.headImg || defAva)

            setToken(data.authorization)
            setUserId(data.user.userId)
            this.token = data.authorization
            this.name = data.user.loginName
            this.avatar = data.user.headImg || defAva
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            // const user = res.user
            // const avatar =
            //   user.avatar == '' || user.avatar == null ? defAva : user.avatar

            // if (res.roles && res.roles.length > 0) {
            //   // 验证返回的roles是否是一个非空数组
            //   this.roles = res.roles
            //   this.permissions = res.permissions
            // } else {
            //   this.roles = ['ROLE_DEFAULT']
            // }
            // this.id = user.userId
            // this.name = user.userName
            // this.avatar = avatar
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        // logout(this.token).then(() => {
        this.token = ''
        this.roles = []
        this.permissions = []
        removeToken()
        removeUserId()
        removeUserName()
        removeUserAvatar()
        resolve()
        localStorage.removeItem('tabIndex')
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },
  },
})

export default useUserStore
